<?php
/**
 * Created by PhpStorm.
 * User: ZhangWei
 * Date: 2018/2/5
 * Time: 20:17
 */

namespace App\Http\Controllers\Api\Mp;


use App\Http\Controllers\Api\ApiBase;
use App\Http\Resources\Media as MediaResources;
use App\Models\Medias;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class MediaController extends ApiBase
{
    public function upload_image(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'file' => 'required|image',
        ], [
            'username.required' => '请上传图片',
            'username.image' => '图片格式不正确',
        ]);
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }
        $file = $request->file('file');
        $disk = "public";
        $path = Storage::disk($disk)->putFileAs('cover/' . $this->getUserHashId(), $file, $file->getClientOriginalName());
        $data['path'] = $path;
        $data['user_id'] = $this->getUserId();
        $data['size'] = $file->getSize();
        $data['suffix'] = $file->extension();
        $data['type'] = 'image';
        $data['mine_type'] = $file->getClientMimeType();
        $data['name'] = $file->getClientOriginalName();

        $media = Medias::query()->updateOrCreate([
            'user_id' => $this->getUserId(),
            'path' => $data['path']
        ], [
            'user_id' => $this->getUserId(),
            'path' => $data['path'],
            'type' => $data['type'],
            'disk' => $disk,
            'suffix' => $data['suffix'],
            'size' => $data['size'],
            'data' => [
                'mine_type' => $data['mine_type']
            ]
        ]);

        $media = new MediaResources($media);

        return $this->success($media);

    }

}